/*
 * @lc app=leetcode.cn id=1305 lang=cpp
 *
 * [1305] 两棵二叉搜索树中的所有元素
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    void inorder(TreeNode *root, vector<int> &result)
    {
        if (root == NULL)
            return;
        inorder(root->left, result);
        result.push_back(root->val);
        inorder(root->right, result);
    }
    vector<int> getAllElements(TreeNode *root1, TreeNode *root2)
    {
        vector<int> result1, result2, ans;
        result1.clear(), result2.clear();
        inorder(root1, result1);
        inorder(root2, result2);

        int i = 0, j = 0;
        while (i < result1.size() || j < result2.size())
        {
            if (j >= result2.size() || (i < result1.size() && result1[i] <= result2[j]))
            {
                ans.push_back(result1[i]);
                i++;
            }
            else
            {
                ans.push_back(result2[j]);
                j++;
            }
        }

        return ans;
    }
};
// @lc code=end
